package com.aat.dizena.chat.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.aat.dizena.base.CommonConstant;
import com.aat.dizena.base.bean.User;
import com.aat.dizena.base.service.UserService;
import com.aat.dizena.base.web.controller.BaseController;
import com.aat.dizena.chat.bean.Msg;
import com.aat.dizena.chat.module.MyWebSocketHandler;
import com.alibaba.fastjson.JSONObject;

/**
 * @time 2016-05-25
 * @author 新歌<xingeking@163.com>
 * @email xingeking@163.com
 * @version v1.0
 * @function 在线用户
 * @info java springMVC
 * @update none
 */
@Controller
@Scope("prototype")
@RequestMapping("chat")
public class IndexChatController extends BaseController {

	@Autowired
	private MyWebSocketHandler handler;
	@Autowired
	private UserService userService;

	// 聊天在线
	@RequestMapping({ "", "/", "index.do" })
	public String index(HttpServletRequest request, Model model) {
		User user = getSessionUser();
		if (user == null) {
			return CommonConstant.WEB_LOGIN_INDEX;
		} else {
			// users.put(user.getUserid(), user);
			request.getSession().setAttribute("uid", user.getId());
			request.getSession().setAttribute("name", user.getNickname());
			
			request.getSession().setAttribute("toUid", "1");// 谁的直播就是谁的ID
		}
		return "/chat/index";
	}

	// 在线人数
	@ResponseBody
	@RequestMapping(value = "getOnline.do", method = RequestMethod.POST)
	public List<Map<String, Object>> getOnline() {
		List<Map<String, Object>> users = new ArrayList<Map<String, Object>>();
		Map<String, WebSocketSession> webs = MyWebSocketHandler.userSocketSessionMap;
		Set<Entry<String, WebSocketSession>> sets = webs.entrySet();
		for (Entry<String, WebSocketSession> entry : sets) {
			String id = entry.getKey();
			User userTmp = userService.queryBean(id);
			Map<String, Object> mapTmp = new HashMap<String, Object>();
			mapTmp.put("uid", userTmp.getId());
			mapTmp.put("uname", userTmp.getNickname());
			mapTmp.put("uflag", userTmp.getFlag());
			users.add(mapTmp);
		}
		return users;
	}

	// 在线人数分页显示
	@ResponseBody
	@RequestMapping(value = "list.do", method = RequestMethod.POST)
	public Map<String, Object> list(@RequestParam(value = "s", required = false, defaultValue = "1") int start,
			@RequestParam(value = "p", required = false, defaultValue = "10") int perPage) {
		List<User> allLists = new ArrayList<User>();
		//
		Map<String, WebSocketSession> webs = MyWebSocketHandler.userSocketSessionMap;
		Set<Entry<String, WebSocketSession>> sets = webs.entrySet();
		for (Entry<String, WebSocketSession> entry : sets) {
			String id = entry.getKey();
			User userTmp = userService.queryBean(id);
			allLists.add(userTmp);
		}
		//
		Long count = 0L + allLists.size();
		Long tmp = count / perPage;
		Long pages = count % perPage == 0 ? tmp : tmp + 1;
		List<User> lists = new ArrayList<User>();
		// 分页操作
		if (start > 0 && start <= pages) {
			int a = (start - 1) * perPage;
			int b = (int) (start * perPage > count ? count : start * perPage);
			lists = allLists.subList(a, b);
		}
		// 返回参数
		Map<String, Object> json = new HashMap<String, Object>();
		json.put("datas", lists);// 数据
		json.put("pages", pages);// 总页
		json.put("start", start);// 页码
		json.put("count", count);// 总数
		return json;
	}

	// 给某个人发信息
	@ResponseBody
	@RequestMapping(value = "msgToOne.do", method = RequestMethod.POST)
	public void msgToOne(@RequestParam("uid") String uid, @RequestParam("txt") String text) {
		try {
			if (isNotEmpty(text)) {
				User user = getSessionUser();
				if (user == null) {

				} else {
					Msg msg = new Msg();
					msg.setDate(new Date());
					msg.setFromUserid(user.getId());
					msg.setFromName(user.getNickname());
					msg.setToUserid(uid);
					msg.setText(text);
					handler.sendMessageToUser(uid, new TextMessage(JSONObject.toJSONString(msg)));
				}
			}

		} catch (IOException e) {

		}
	}

	// 发布系统广播（群发）
	@ResponseBody
	@RequestMapping(value = "msgToAll.do", method = RequestMethod.POST)
	public void msgToAll(@RequestParam("txt") String text) {
		try {
			if (isNotEmpty(text)) {
				User user = getSessionUser();
				if (user == null) {

				} else {
					if (chkAuth("*:*:msgToAll")) {
						Msg msg = new Msg();
						msg.setDate(new Date());
						msg.setFromUserid(getSessionUser().getId());
						msg.setFromName("系统广播");
						msg.setToUserid("all");
						msg.setText(text);
						handler.broadcast(user.getId(), new TextMessage(JSONObject.toJSONString(msg)));
					}
				}
			}
		} catch (IOException e) {

		}

	}

	// 发布群组在线人员（群发）
	@ResponseBody
	@RequestMapping(value = "msgToGroup.do", method = RequestMethod.POST)
	public void msgToGroup(@RequestParam("gid") String gid, @RequestParam("txt") String text) {
		try {
			if (isNotEmpty(text)) {
				User user = getSessionUser();
				if (user == null) {

				} else {
					Msg msg = new Msg();
					msg.setDate(new Date());
					msg.setFromUserid(user.getId());
					msg.setFromName(user.getNickname());
					msg.setToUserid(gid);
					msg.setText(text);
					handler.talkGroup(user.getId(), gid, new TextMessage(JSONObject.toJSONString(msg)));
				}
			}
		} catch (Exception e) {

		}
	}

}
